package com.dongdongshop.shiro;
import com.dongdongshop.admin.model.User;
import com.dongdongshop.api.SellerServiceApi;
import com.dongdongshop.common.Result;
import com.dongdongshop.dto.SellerDTO;
import com.dongdongshop.em.TokenEnum;
import com.dongdongshop.exception.LoginException;
import com.dongdongshop.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(LoginRealm.class);
    @Autowired
    private UserService userService;

    @Autowired
    private SellerServiceApi sellerServiceApi;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User admin = (User) SecurityUtils.getSubject().getPrincipal();
        logger.info("授权,用户{}",admin.getUname());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    //登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("登录");
        //从数据库中查询数据
        //获取subject.login方法传入的信息, 强转
        LoginToken token = (LoginToken) authenticationToken;
        TokenEnum tokenEnum = token.getTokenEnum();
        String username = token.getUsername();//前台传入的用户名
        if (token.getTokenEnum().equals(TokenEnum.ADMIN)) {
            User admin = userService.findUserByName(username);
            if (admin == null) {
                return null;
            }
            //                          数据库中的用户         密码                 获取盐密码解密                          类名,随便给也行
            return new SimpleAuthenticationInfo(admin, admin.getPwd(), ByteSource.Util.bytes(admin.getSalt()),"LoginRealm");
        }else if (token.getTokenEnum().equals(TokenEnum.SELLER)){
            Result<SellerDTO> result = sellerServiceApi.getSellerByName(username);
            SellerDTO sellerDTO = result.getData();
            if (sellerDTO == null){
                return null;
            }
            if (!sellerDTO.getStatus().equals("1")){
                throw  new LoginException("账号异常,请联系客服人员");
            }
            return new SimpleAuthenticationInfo(sellerDTO, sellerDTO.getPassword(), ByteSource.Util.bytes(sellerDTO.getSalt()),"LoginRealm");
        }
       return null;
    }
}
